package com.scf.filter;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.DelegatingFilterProxy;

/**
 * 过滤器自动配置类
 *
 * @author sunchuanfu
 * @since 2025/7/1
 */
@Configuration
public class Filter1Config {

    /**
     * 注册过滤器 -- 方式一
     */
    @Bean
    public FilterRegistrationBean<Filter1> registerFilter1() {
        FilterRegistrationBean<Filter1> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new Filter1());
        registrationBean.addUrlPatterns("/demo/hello");// 注：这里要用全路径名，不匹配"/hello"
        registrationBean.setName("filter1");
        registrationBean.setOrder(1);
        return registrationBean;
    }

    @Bean("filter1")
    public Filter1 filter1() {
        return new Filter1();
    }

    /**
     * 注册过滤器 -- 方式二
     */
    @Bean
    public FilterRegistrationBean<DelegatingFilterProxy> registerFilter2() {
        FilterRegistrationBean<DelegatingFilterProxy> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new DelegatingFilterProxy());// 创建DelegatingFilterProxy对象
        registrationBean.addInitParameter("targetBeanName", "filter1");// 指定被代理的过滤器
        registrationBean.addInitParameter("targetFilterLifecycle", "true");
        registrationBean.addUrlPatterns("/demo/hello");
        registrationBean.setName("filter1");
        registrationBean.setOrder(2);
        return registrationBean;
    }

}
